<?php

namespace App\Models\Admin\Apis;


class ApisModel extends BaseApisModel
{
    protected $table = 'apis';

    /**
     * 获取所有api列表
     *
     * @param array $fields
     * @return mixed
     */
    public function getAllList(array $fields = self::QUERY_DEFAULT_FIELDS)
    {
        return $this->select($fields)
            ->where('deleted', self::DELETED_NO)
            ->get()
            ->toArray();
    }

    /**
     * 获取总条数
     *
     * @param array $params
     * @return mixed
     */
    public function getTotal(array $params)
    {
        return $this->_listHandleWhere($this, $params)
            ->count();
    }

    /**
     * 获取列表
     *
     * @param array $params
     * @param array $fields
     * @return mixed
     */
    public function getList(array $params, array $fields = self::QUERY_DEFAULT_FIELDS)
    {
        $query = $this->select($fields);
        $query = $this->_listHandleWhere($query, $params);
        return $query
            ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
            ->limit(PAGE_SIZE)
            ->get()
            ->toArray();
    }

    /**
     * 根据path查询数据
     *
     * @param string $path
     * @param array  $fields
     * @return mixed
     */
    public function getItemByPath(string $path, array $fields = self::QUERY_DEFAULT_FIELDS)
    {
        $result = $this->select($fields)
            ->where('path', $path)
            ->where('deleted', self::DELETED_NO)
            ->first();
        return $result ? $result->toArray() : [];
    }

    private function _listHandleWhere($query, array $params)
    {
        if (!empty($params['path'])) {
            $query = $query->where('path', $params['path']);
        }
        if (!empty($params['description'])) {
            $query = $query->where('description', $params['description']);
        }
        if (!empty($params['apiGroup'])) {
            $query = $query->where('api_group', $params['apiGroup']);
        }
        if (!empty($params['method'])) {
            $query = $query->where('method', $params['method']);
        }

        return $query->where('deleted', self::DELETED_NO);
    }
}
